<?php
$options = getopt('u:p:');

$headers = [
   'accept-encoding'=> 'gzip, deflate, br',
    'accept-language'=> 'zh-CN,zh;q=0.9',
    'user-agent' => 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
    'origin' => 'https://www.nunuyy.com',
    'referer' => 'https://www.nunuyy.com/',
    'sec-ch-ua' => '"Chromium";v="88", "Google Chrome";v="88", ";Not A Brand";v="99"',
    'sec-ch-ua-mobile' => '?0',
    'sec-fetch-dest'=>'empty',
    'sec-fetch-mode' => 'cors',
    'sec-fetch-site'=>'cross-site'

];
$header = '';
foreach ($headers as $k=>$v) {
    $header .= "{$k}:{$v}\r\n";
}
$context = stream_context_create([
    'http' =>[
        'method' => 'GET',
        'header' => $header,
        'proxy' => $options['p'],
        'protocol_version' => 1.1,
       // 'ignore_errors' => false
    ],
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false
    ]
]);

$seg = 1;
$fn = time().'.ts';
$save = fopen($fn, 'wb+');
$bufferSize = 1024 * 1024;
while (true) {
	//$url = "https://ev-h.phncdn.com/hls/videos/202008/22/344938221/,1080P_4000K,720P_4000K,480P_2000K,240P_400K,_344938221.mp4.urlset/seg-{$seg}-f2-v1-a1.ts?validfrom=1612855654&validto=1612862854&hdl=-1&hash=xsTQ9ZFVuqrdU1OFJ55nmpzHPA8%3D";

    try {
        $fp = fopen($options['u'], 'rb', false,$context);
        if (!$fp) {
            break;
        }
        //$meta = stream_get_meta_data($fp);

        while (!feof($fp)) {
            fwrite($save, fread($fp, $bufferSize));
        }
        echo $seg,PHP_EOL;
        fclose($fp);
        $seg++;
    } catch (Throwable $throwable) {
    	var_dump($throwable);
        fclose($fp);
        break;
    }

}

shell_exec("ffmpeg -i {$fn} -c copy ".(pathinfo($fn)['filename']).'.mp4 -hide_banner');
fclose($save);
